/**
 * Axios 实例创建工具
 */
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import type { ApiConfig, BackendType } from '@/config/axios.config'

/** 统一响应数据格式 */
interface ApiResponse<T = unknown> {
  data: T
  message?: string
}

/** 创建 Axios 实例 */
export function createAxiosInstance(config: ApiConfig, backend: BackendType): AxiosInstance {
  const instance = axios.create(config)

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // 添加认证头
      const token = localStorage.getItem(`${backend}_auth_token`)
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }

      // 添加请求ID
      config.headers['X-Request-ID'] =
        `${backend}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

      console.log(`[${backend.toUpperCase()} API] ${config.method?.toUpperCase()} ${config.url}`)
      return config
    },
    (error) => {
      console.error(`[${backend.toUpperCase()} API] 请求错误:`, error)
      return Promise.reject(error)
    },
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      // 返回完整的响应对象，保持 code、message、data、pagination 等信息
      return response.data
    },
    (error) => {
      console.error(`[${backend.toUpperCase()} API] 响应错误:`, error)

      // 处理认证过期
      if (error.response?.status === 401) {
        localStorage.removeItem(`${backend}_auth_token`)
        window.dispatchEvent(new CustomEvent(`${backend}-auth-expired`))
      }

      return Promise.reject(error)
    },
  )

  return instance
}

/** 创建所有后端的 Axios 实例 */
export function createAllAxiosInstances(configs: Record<BackendType, ApiConfig>) {
  const instances: Record<BackendType, AxiosInstance> = {} as Record<BackendType, AxiosInstance>

  Object.entries(configs).forEach(([backend, config]) => {
    instances[backend as BackendType] = createAxiosInstance(config, backend as BackendType)
  })

  return instances
}
